package com.ymt.reliable.message.queue.activemq.service.impl;

import com.ymt.reliable.message.queue.service.MessageQueueService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

/**
 * 基于 ActiveMq 实现类
 */
@Service
@ConditionalOnProperty(prefix = "activeMq", name = "url", matchIfMissing = false)
public class ActiveMqServiceImpl implements MessageQueueService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ActiveMqServiceImpl.class);

    public ActiveMqServiceImpl() {
        LOGGER.info(">>> 实例化{}服务", "ActiveMqServiceImpl");
    }

    @Autowired
    private JmsTemplate jmsTemplate;

    @Override
    public void sendMessageToMessageQueue(String queueName, final String messageId, final String messageBody) {
        jmsTemplate.send(queueName, new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                TextMessage message = session.createTextMessage(messageBody);
                message.setStringProperty("messageId", messageId);
                return message;
            }
        });
        LOGGER.info(">>> 发送消息到mq 队列:{},消息内容:{}", queueName, messageBody);
    }
}
